// Gem.ts

import { Util } from "../Util";
import { EItemAffix, IItem, EItemQuality, EItemType, EAffixType } from "./Item";

// 宝石类型（具体宝石类别）
export enum EGemType {
    Red = "Red", // 加力量
    Green = "Green", // 加身法
    Blue = "Blue", // 加悟性
    Yellow = "Yellow", // 加体质
    Purple = "Purple", // 全属性
}

// 宝石接口 - 继承 IItem
export interface IGem extends IItem {
    gemType: EGemType;
    affixes: EItemAffix[];
    level?: number; // 宝石等级（可选）
}

export class Gem implements IGem {
    // IItem 实现
    id: string;
    uid: string = '';
    name: string;
    count: number;
    icon: string;
    itemType: EItemType = EItemType.Gem;
    desc: string;
    quality: EItemQuality;
    stackable: boolean = true;
    price: number;

    // IGem 特有属性
    gemType: EGemType;
    affixes: EItemAffix[];
    level: number = 0;

    constructor(base: IGem) {
        this.id = base.id;
        this.uid = base.uid || Util.generateRandomId(); // 使用传入的uid或生成新的
        this.name = base.name;
        this.count = base.count || 1;
        this.icon = base.icon;
        this.desc = base.desc || "";
        this.quality = base.quality;
        this.gemType = base.gemType;
        this.affixes = base.affixes || [];
        this.level = base.level || 0;
        
        // 计算价格
        this.price = this.getPrice();
    }

    // 获取价格
    private getPrice(): number {
        // 宝石价格 = 等级 * 100
        return (this.level || 1) * 100;
    }

    // 序列化宝石数据
    getPackage(): any {
        return {
            id: this.id,
            uid: this.uid,
            name: this.name,
            count: this.count,
            itemType: this.itemType,
            quality: this.quality,
            icon: this.icon,
            desc: this.desc,
            stackable: this.stackable,
            price: this.price,
            gemType: this.gemType,
            level: this.level,
            affixes: this.affixes.map(affix => ({
                type: affix.type,
                value: affix.value,
                isPercentage: affix.isPercentage,
                description: affix.description
            }))
        };
    }

    // 从序列化数据恢复宝石
    setPackage(data: any): void {
        if (!data) return;
        
        // 恢复基本属性
        this.id = data.id;
        this.uid = data.uid || '';
        this.name = data.name;
        this.count = data.count || 1;
        this.quality = data.quality;
        this.icon = data.icon;
        this.desc = data.desc || "";
        this.stackable = data.stackable !== undefined ? data.stackable : true;
        this.price = data.price || this.getPrice();
        this.gemType = data.gemType;
        this.level = data.level || 0;
        
        // 恢复词缀
        this.affixes = [];
        if (Array.isArray(data.affixes)) {
            this.affixes = data.affixes.map((affixData: any) => ({
                type: affixData.type,
                value: affixData.value,
                isPercentage: affixData.isPercentage,
                description: affixData.description
            }));
        }
    }

    // 静态工厂方法 - 从数据创建宝石实例
    static fromData(data: any): Gem {
        return new Gem({
            id: data.id,
            itemType: EItemType.Gem,
            uid: data.uid,
            name: data.name,
            count: data.count,
            icon: data.icon,
            desc: data.desc,
            quality: data.quality,
            gemType: data.gemType,
            affixes: data.affixes || [],
            level: data.level,
            price: data.price,
            stackable: data.stackable !== undefined ? data.stackable : true
        });
    }

    // 升级宝石
    upgrade(): boolean {
        const maxLevel = 10; // 最大等级
        if (this.level >= maxLevel) return false;
        
        this.level++;
        this.price = this.getPrice(); // 更新价格
        
        // 升级效果：增强词缀
        for (const affix of this.affixes) {
            // 每级增加10%效果
            affix.value *= 1.1;
            if (!affix.isPercentage) {
                affix.value = Math.round(affix.value);
            }
            // 更新描述
            affix.description = this.getAffixDescription(affix.type, affix.value, affix.isPercentage);
        }
        
        return true;
    }

    // 获取词缀描述（与Equipment保持一致）
    private getAffixDescription(type: EAffixType, value: number, isPercentage: boolean): string {
        const formattedValue = isPercentage ? 
            `${(value * 100).toFixed(0)}%` : 
            value.toFixed(0);

        // 这里可以复用Equipment中的描述逻辑，或者根据宝石特性自定义
        switch (type) {
            case EAffixType.Strength: return `力量 +${formattedValue}`;
            case EAffixType.Agility: return `身法 +${formattedValue}`;
            case EAffixType.Intelligence: return `悟性 +${formattedValue}`;
            case EAffixType.Vitality: return `体质 +${formattedValue}`;
            case EAffixType.AllBaseAttributes: return `全属性 +${formattedValue}`;
            case EAffixType.Attack: return `攻击力 +${formattedValue}`;
            case EAffixType.Defense: return `防御力 +${formattedValue}`;
            case EAffixType.Hp: return `生命值 +${formattedValue}`;
            default: return "未知属性";
        }
    }

    // 计算宝石评分（可选功能）
    calculateScore(): number {
        let score = 0;
        
        // 基础评分（品质 + 等级）
        const qualityMultipliers = {
            [EItemQuality.Common]: 1,
            [EItemQuality.Uncommon]: 2,
            [EItemQuality.Rare]: 4,
            [EItemQuality.Epic]: 8,
            [EItemQuality.Legendary]: 16,
            [EItemQuality.Artifact]: 32
        };
        
        score += qualityMultipliers[this.quality] * 10 * this.level;
        
        // 词缀评分
        for (const affix of this.affixes) {
            const value = affix.isPercentage ? affix.value * 100 : affix.value;
            score += value * this.level * 5; // 简单的评分公式
        }
        
        return Math.round(score);
    }
}

// 添加类型守卫函数
export function isGem(item: IItem): item is IGem {
    return item.itemType === EItemType.Gem;
}